//
//  KZSegmentView.swift
//  KZSwiftMoudel
//
//  Created by 朱凯 on 2018/6/26.
//  Copyright © 2018年 JooKey. All rights reserved.
//

import UIKit

struct KZSegmentConfig {
    
    var backgroundColor: UIColor = UIColor.white    // 背景颜色
    var titleNormalColor: UIColor = UIColor.black   // 标题色
    var titleSelectColor: UIColor = UIColor.red     // 标题选中色
    
    var titleFont: UIFont = UIFont.systemFont(ofSize: 15)
    
    var titleAdaptWidth: Bool = false {             // 标题宽度自适应，true的话等宽
        didSet {
            if titleAdaptWidth == true {
                indicatorAdaptTitleWidth = true
            }
            
        }
    }
  
  
    
    var titleMaxCount: Int = 5                      // 等宽时，非滑动可显示的最大标题数
    
    
    var indicatorColor: UIColor = UIColor.red       // 指示器颜色
    var indicatorAdaptTitleWidth: Bool = false {    // 如果宽度自适应，则指示器也自适应
        didSet {
            if titleAdaptWidth == true && indicatorAdaptTitleWidth == false {
                indicatorAdaptTitleWidth = true
            }
        }
    }
    var indicatorHeight: CGFloat = 5                // 指示器高度
    var indicatorBottomOffset: CGFloat = 0.0        // 指示器距父视图底部的便宜
}

class KZSegmentView: UIView {
    
    private var scroll: UIScrollView! = nil
    private let indicatorView = UIView()
    
    var segmentClickHandler: (Int) -> Void = {_ in }
    
    /// 配置
    var config = KZSegmentConfig() {
        didSet {
            setNeedsLayout()
        }
    }
    /// 标题数
    var titles: [String] = [String]() {
        didSet {
            setNeedsLayout()
        }
    }

    convenience init() {
        self.init(frame: .zero)
    }
}


// MARK: ------ 创建视图
extension KZSegmentView {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard titles.count > 0 else { return }
        guard scroll == nil else { return }
        
        setupUI()
    }
    
    func setupUI() {
        
        self.backgroundColor = config.backgroundColor
    

        scroll = UIScrollView()
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        scroll.bounces = false
        self.addSubview(scroll)
        scroll.snp.makeConstraints { (m) in
            m.edges.equalTo(self)
        }
        
        var last: UIButton? = nil
        var first: UIButton!
        for (i, title) in titles.enumerated() {
            
            let button = UIButton(type: .custom)
            button.tag = i + 10
            button.addTarget(self, action: #selector(onButtonClick(button:)), for: .touchUpInside)
            button.setTitle(title, for: .normal)
            button.titleLabel?.font = config.titleFont
            button.setTitleColor(config.titleNormalColor, for: .normal)
            button.setTitleColor(config.titleSelectColor, for: .selected)
            scroll.addSubview(button)
            
            if i == 0 {
                first = button
                button.isSelected = true
            }
            
            button.snp.makeConstraints { (m) in
                m.top.height.equalTo(scroll)
                if let last = last {
                    m.left.equalTo(last.snp.right)
                } else {
                    m.left.equalTo(0)
                }
                // 宽度自适应
                if config.titleAdaptWidth {
                    m.width.equalTo(title.width(fontSize: config.titleFont.pointSize) + 20)
                } else {
                    if titles.count > config.titleMaxCount {
                        m.width.equalTo(scroll).multipliedBy(1.0 / config.titleMaxCount.float)
                    } else {
                        m.width.equalTo(scroll).multipliedBy(1.0 / titles.count.float)
                    }
                }
            }
            
            last = button
        }
        
        
        
        indicatorView.backgroundColor = config.indicatorColor
        scroll.addSubview(indicatorView)
        indicatorView.snp.makeConstraints { (m) in
            m.height.equalTo(config.indicatorHeight)
            m.bottom.equalTo(first).offset(-config.indicatorBottomOffset)

            m.centerX.equalTo(first)

            if config.indicatorAdaptTitleWidth {
                m.width.equalTo(first.titleLabel!.text!.width(fontSize: self.config.titleFont.pointSize))
            } else {
                if titles.count > config.titleMaxCount {
                    m.width.equalTo(scroll).multipliedBy(1.0 / config.titleMaxCount.float)
                } else {
                    m.width.equalTo(scroll).multipliedBy(1.0 / titles.count.float)
                }
            }
        }
        
        
        scroll.layoutIfNeeded()
        scroll.contentSize.width = last!.right
    }
    
    
}

// MARK: ------ 事件
extension KZSegmentView {
    
    func selectIndex(index: Int) {
        
        onButtonClick(button: scroll.viewWithTag(index + 10) as! UIButton)
    }
    
    @objc func onButtonClick(button: UIButton) {
        
        
        
        for subview in scroll.subviews {
            if let subview = subview as? UIButton {
                subview.isSelected = false
            }
            
        }
        
        button.isSelected = true
        self.segmentClickHandler(button.tag - 10)
        
        UIView.animate(withDuration: 0.25) {
            self.indicatorView.snp.remakeConstraints { (m) in
                m.height.equalTo(self.config.indicatorHeight)
                m.bottom.equalTo(button).offset(-self.config.indicatorBottomOffset)
                
                m.centerX.equalTo(button)
                if self.config.indicatorAdaptTitleWidth {
                    m.width.equalTo(button.titleLabel!.text!.width(fontSize: self.config.titleFont.pointSize))
                } else {
                    if self.titles.count > self.config.titleMaxCount {
                        m.width.equalTo(self.scroll).multipliedBy(1.0 / self.config.titleMaxCount.float)
                    } else {
                        m.width.equalTo(self.scroll).multipliedBy(1.0 / self.titles.count.float)
                    }
                }
            }
            self.layoutIfNeeded()
            
            // 可滑动
            if self.scroll.contentSize.width > self.scroll.width {
                let offset = self.indicatorView.x - self.scroll.width / 2
                let delt = self.scroll.contentSize.width - self.scroll.width
                if offset <= 0 {
                    self.scroll.contentOffset.x = 0
                } else if offset > 0 && offset < delt {
                    self.scroll.contentOffset.x = offset
                } else {
                    self.scroll.contentOffset.x = delt
                }
            }
            
        }
        
    }
}
